package client

import (
	"fmt"
	"gin-gorm-learn/cfg"
	"gin-gorm-learn/model"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

var db *gorm.DB
var err error

type MysqlTask struct{}

func init() {
	db, err = gorm.Open("mysql", cfg.MYSQL_DST)
	if err != nil {
		fmt.Println("Client init catch error =", err)
	}
}
func ping() error {
	err := db.DB().Ping()
	if err != nil {
		db, err = gorm.Open("mysql", cfg.MYSQL_DST)
		if err != nil {
			fmt.Println("Client reconnect catch error =", err)
			return err
		}
	}
	return nil
}

func (t MysqlTask) ReConnect() (*gorm.DB, error) {
	err := ping()
	if err != nil {
		return nil, err
	}
	return db, nil
}

func (t MysqlTask) AutoMigrate() *gorm.DB {
	result := db.AutoMigrate(&model.VideoInfo{})
	if result.Error != nil {
		fmt.Println("migrate VideoInfo catch error =", result.Error)
		return result
	}
	result = db.AutoMigrate(&model.AuthorInfo{})
	result = db.AutoMigrate(&model.GormSingleTask{})
	result = db.AutoMigrate(&model.DownloadRecord{})
	result = db.AutoMigrate(&model.TaskRecord{})
	return result
}

func (t MysqlTask) InsertItem(item *model.VideoInfo) (*gorm.DB, error) {
	ping()
	result := db.Save(item)
	if result.RowsAffected != 0 {
		// success save into db
		return result, nil
	}
	return nil, result.Error
}
